﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entities;
using BL;
using DA;
using System.Text.RegularExpressions;
using ERP.Membership;

namespace ERP
{
    public partial class UserForm : BaseERPPage
    {
        RoleManager roleManager = new RoleManager();
        UserManager userManager = new UserManager();

        string userIdString;
        int? userId;

        public UserForm()
            :base (Permission.Admin)
        {

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                userIdString = Request.QueryString.Get("UserId");
                userId = userIdString.ToInt();

                checkboxlistRoles.DataSource = roleManager.GetAllRoles();
                checkboxlistRoles.DataTextField = "Name";
                checkboxlistRoles.DataValueField = "RoleId";
                checkboxlistRoles.DataBind();

                checkboxlistPermissions.DataSource = Enum.GetNames(typeof(Permission));
                checkboxlistPermissions.DataBind();

                if (userId.HasValue)
                {
                    if (userManager.UserExist(userId.Value))
                    {
                        ERP_Users user = userManager.GetUser(userId.Value);
                        txtFirstName.Text = user.FirstName;
                        txtLastName.Text = user.LastName;
                        txtPassword.Text = user.Password;
                        txtEmail.Text = user.EMail;

                        if (!string.IsNullOrWhiteSpace(user.Roles))
                        {
                            string[] userRoles = user.Roles.Split(',');

                            foreach (ListItem item in checkboxlistRoles.Items)
                            {
                                if (userRoles.Contains(item.Value))
                                {
                                    item.Selected = true;
                                }
                            }
                        }

                        Permission ItemPermission;
                        Permission userPermissions = (Permission)Enum.ToObject(typeof(Permission), long.Parse(user.Permissions));
                        
                        foreach (ListItem item in checkboxlistPermissions.Items)
                        {
                            if (Enum.TryParse(item.Value, out ItemPermission))
                            {
                                if (userPermissions.HasFlag(ItemPermission))
                                {
                                    item.Selected = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        ShowError("The user was not found.");
                    }
                }
            }
        }

        public void btnSubmit_OnClick(object sender, EventArgs e)
        {
            userIdString = Request.QueryString.Get("UserId");
            userId = userIdString.ToInt();

            Permission itemPermission;
            long permissions = 0;

            foreach (ListItem item in checkboxlistPermissions.Items)
            {
                if (item.Selected && Enum.TryParse(item.Value, out itemPermission))
                {
                    permissions = permissions | (long)itemPermission;
                }
            }

            string roles = string.Empty;

            foreach (ListItem item in checkboxlistRoles.Items)
            {
                if (item.Selected)
                {
                    roles += item.Value + ",";
                }
            }

            roles = roles.TrimEnd(',');

            if (userId.HasValue)
            {
                if (userManager.UserExist(userId.Value))
                {
                    ERP_Users user = new ERP_Users()
                        {
                            UserId = userId.Value,
                            FirstName = txtFirstName.Text,
                            LastName = txtLastName.Text,
                            Password = txtPassword.Text,
                            EMail = txtEmail.Text,
                            Roles = roles,
                            Permissions = permissions.ToString()
                        };

                    if (userManager.EditUser(user))
                    {
                        ShowError("The user was updated.");
                        lblMessage.CssClass = "valid";
                    }
                    else
                    {
                        ShowError("Error. The user was not updated.");
                        lblMessage.CssClass = "failureNotification";
                    }
                }
            }
            else
            {
                ERP_Users user = new ERP_Users()
                    {
                        Password = txtPassword.Text,
                        EMail = txtEmail.Text,
                        FirstName = txtFirstName.Text,
                        LastName = txtLastName.Text,
                        Roles = roles,
                        Permissions = permissions.ToString()
                    };

                if (userManager.AddUser(user))
                {
                    ShowError("The user was created.");
                    lblMessage.CssClass = "valid";
                }
                else
                {
                    ShowError("Error. The user was not created.");
                    lblMessage.CssClass = "failureNotification";
                }
            }
        }

        private void ShowError(string message)
        {
            this.lblMessage.Text = message;
            this.lblMessage.Visible = true;
        }
    }
}